package entity

import (
	"fmt"
	"time"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/workflow"
	"shqsoft.cn/pasnj/workflow/entity"

	"github.com/jinzhu/gorm"
)

//IndiClieDiviFlowAppXJK 零售客户认定审批
type IndiClieDiviFlowAppXJK struct {
	ID         int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	IDNO       string    `gorm:"column:IDNO"`
	CUID       int       `gorm:"column:CUID"`
	UTID       int       `gorm:"column:UTID"`
	ACNO       string    `gorm:"column:ACNO"`
	BANO       string    `gorm:"column:BANO"`
	ACID       int       `gorm:"column:ACID"`
	OPDT       time.Time `gorm:"column:OPDT"`
	CUNM       string    `gorm:"column:CUNM"`
	UTNM       string    `gorm:"column:UTNM"`
	ITNM       string    `gorm:"column:ITNM"`
	EMNO1      string    `gorm:"column:EMNO1"`
	EMID1      int       `gorm:"column:EMID1"`
	EMNM1      string    `gorm:"-" json:"emnm1"`
	DSVL1      float64   `gorm:"column:DSVL1"`
	EMNO2      string    `gorm:"column:EMNO2"`
	EMNM2      string    `gorm:"-" json:"emnm2"`
	EMID2      int       `gorm:"column:EMID2"`
	DSVL2      float64   `gorm:"column:DSVL2"`
	EMNO3      string    `gorm:"column:EMNO3"`
	EMNM3      string    `gorm:"-" json:"emnm3"`
	EMID3      int       `gorm:"column:EMID3"`
	DSVL3      float64   `gorm:"column:DSVL3"`
	JYJG       string    `gorm:"column:JYJG"`
	DSDT       time.Time `gorm:"column:DSDT"`
	UID        int       `gorm:"column:UID"`
	FRID       int       `gorm:"column:FRID"`
	Progress   float64   `gorm:"-" json:"progress"`
	StepName   string    `gorm:"-" json:"stepName"`
	Status     string    `gorm:"-" json:"status"`
	STEP       int       `gorm:"-" json:"step"`
	THSM       string    `gorm:"column:THSM"`
	SQR        string    `gorm:"column:SQR"`
	SQR2       string    `gorm:"column:SQR2"`
	SQR3       string    `gorm:"column:SQR3"`
	CREATETIME time.Time `gorm:"column:CREATETIME"`
	UPDATETIME time.Time `gorm:"column:UPDATETIME"`
	XM1        string    `gorm:"column:XM1;"`
	LXFS1      string    `gorm:"column:LXFS1;"`
	XB1        string    `gorm:"column:XB1;"`
	ZJHM1      string    `gorm:"column:ZJHM1;"`
	GZDW1      string    `gorm:"column:GZDW1;"`
	QSGX1      string    `gorm:"column:QSGX1;"`
	SD1        string    `gorm:"column:SD1;"`
	BZ1        string    `gorm:"column:BZ1;"`
	XM2        string    `gorm:"column:XM2;"`
	LXFS2      string    `gorm:"column:LXFS2;"`
	XB2        string    `gorm:"column:XB2;"`
	ZJHM2      string    `gorm:"column:ZJHM2;"`
	GZDW2      string    `gorm:"column:GZDW2;"`
	QSGX2      string    `gorm:"column:QSGX2;"`
	SD2        string    `gorm:"column:SD2;"`
	BZ2        string    `gorm:"column:BZ2;"`
	XM3        string    `gorm:"column:XM3;"`
	LXFS3      string    `gorm:"column:LXFS3;"`
	XB3        string    `gorm:"column:XB3;"`
	ZJHM3      string    `gorm:"column:ZJHM3;"`
	GZDW3      string    `gorm:"column:GZDW3;"`
	QSGX3      string    `gorm:"column:QSGX3;"`
	SD3        string    `gorm:"column:SD3;"`
	BZ3        string    `gorm:"column:BZ3;"`
	XM4        string    `gorm:"column:XM4;"`
	LXFS4      string    `gorm:"column:LXFS4;"`
	XB4        string    `gorm:"column:XB4;"`
	ZJHM4      string    `gorm:"column:ZJHM4;"`
	GZDW4      string    `gorm:"column:GZDW4;"`
	QSGX4      string    `gorm:"column:QSGX4;"`
	SD4        string    `gorm:"column:SD4;"`
	BZ4        string    `gorm:"column:BZ4;"`
	XM5        string    `gorm:"column:XM5;"`
	LXFS5      string    `gorm:"column:LXFS5;"`
	XB5        string    `gorm:"column:XB5;"`
	ZJHM5      string    `gorm:"column:ZJHM5;"`
	GZDW5      string    `gorm:"column:GZDW5;"`
	QSGX5      string    `gorm:"column:QSGX5;"`
	SD5        string    `gorm:"column:SD5;"`
	BZ5        string    `gorm:"column:BZ5;"`
	XM6        string    `gorm:"column:XM6;"`
	LXFS6      string    `gorm:"column:LXFS6;"`
	XB6        string    `gorm:"column:XB6;"`
	ZJHM6      string    `gorm:"column:ZJHM6;"`
	GZDW6      string    `gorm:"column:GZDW6;"`
	QSGX6      string    `gorm:"column:QSGX6;"`
	SD6        string    `gorm:"column:SD6;"`
	BZ6        string    `gorm:"column:BZ6;"`
	ISGHR      int       `gorm:"-" json:"isghr"`
}

//TableName User用户表名
func (IndiClieDiviFlowAppXJK) TableName() string {
	return "T_INDI_CLIE_DIVI_XJK"
}

//BeforeSave 保存前的触发器
func (i *IndiClieDiviFlowAppXJK) BeforeSave(tx *gorm.DB) (err error) {
	row := tx.Raw("select JZDATE,BACKDATE from dbo.GetFlowDate()").Row()
	var jzDate time.Time
	var zsDate time.Time
	row.Scan(&jzDate, &zsDate)
	if i.DSDT.Unix() < zsDate.Unix() {
		err = fmt.Errorf("已过认定截止日%s，认定日期不能早于%s！", jzDate.Format("2006-01-02"), zsDate.Format("2006-01-02"))
		return
	}
	var ret int
	row = tx.Raw("select COUNT(*) ret from T_INDI_CLIE_DIVI_XJK where LXFS1=? or LXFS2=?", i.LXFS1, i.LXFS1).Row()
	row.Scan(&ret)
	if ret == 5 {
		return fmt.Errorf("亲属的联系方式在系统已存在5个，请正确填写亲属信息")
	}
	sqlstr := "select OPDT,CUNM,ID CUID,UTID,UTNM from V_INDI_CLIE_FLOW WHERE IDNO=? AND ISXJK=1"
	row = tx.Raw(sqlstr, i.IDNO).Row()
	row.Scan(&i.OPDT, &i.CUNM, &i.CUID, &i.UTID, &i.UTNM)
	if i.CUID == 0 {
		return fmt.Errorf("证件号码:%s在系统中未开通小京卡！", i.IDNO)
	}
	var emid1 int
	sql := "select ID,SysUserName from T_SysUser where SysUserID=?"
	row = tx.Raw(sql, i.EMNO1).Row()
	row.Scan(&emid1, &i.SQR)
	if emid1 == 0 {
		return fmt.Errorf("员工号1:%s在系统中没有找到！", i.EMNO1)
	}
	i.EMID1 = emid1
	if i.UID == 0 {
		i.UID = i.EMID1
	}
	var emid2 int
	row = tx.Raw("select ID,SysUserName from T_SysUser where SysUserID=? AND ISLSGHR=1", i.EMNO2).Row()
	row.Scan(&emid2, &i.SQR2)
	if emid2 == 0 {
		return fmt.Errorf("员工号:【%s】无管户资格，不是管户人", i.EMNO2)
	}
	i.EMID2 = emid2

	if i.DSVL2 < 10 {
		return fmt.Errorf("管户人【%s】的占比最少10%", i.EMNO2)
	}
	var count int
	if i.ID == 0 {
		sql = "select count(a.ID) from T_INDI_CLIE_DIVI_XJK a inner join T_FLOW_RUN b on a.FRID=b.ID where b.STATE=0 and a.CUID=?"
		row = tx.Raw(sql, i.CUID).Row()
		row.Scan(&count)
		if count > 0 {
			return fmt.Errorf("客户:%s(%s)已经在申请中，不能重复申请！", i.CUNM, i.IDNO)
		}
	}
	if i.ID > 0 {
		row := base.DB.Model(IndiClieDiviFlowAppXJK{}).Where("ID=?", i.ID).Select("FRID").Row()
		row.Scan(&i.FRID)
	}
	sqlEx := "select PDID from dim_user where emid=?"
	row = tx.Raw(sqlEx, i.UID).Row()
	var utid int
	row.Scan(&utid)
	if utid == 131 {
		return fmt.Errorf("错误的申请，申请失败！")
	}
	if i.FRID == 0 {
		wfid := 25
		runid, err := workflow.Create(wfid, i.UID, tx)
		if err != nil {
			return err
		}
		i.FRID = runid
	}
	i.CREATETIME = time.Now()
	i.UPDATETIME = time.Now()
	return
}

func (i *IndiClieDiviFlowAppXJK) AfterDelete(tx *gorm.DB) (err error) {
	if i.FRID > 0 {
		return workflow.Delete(i.FRID)
	}
	return nil
}

// AfterFind 查询后触发器
func (i *IndiClieDiviFlowAppXJK) AfterFind(tx *gorm.DB) (err error) {
	sqlEx := "select SysUserName from T_SysUser where ID = ?"
	row := tx.Raw(sqlEx, i.EMID1).Row()
	row.Scan(&i.EMNM1)
	if i.FRID == 0 {
		i.Status = "exception"
		i.StepName = "校验错误"
		return
	}
	sqlEx = "select count(*) ISGHR from T_SysUser where ID in(select EMID2 from T_INDI_CLIE_DIVI_XJK where FRID=?) AND ISLSGHR=1"
	row = tx.Raw(sqlEx, i.FRID).Row()
	row.Scan(&i.ISGHR)

	run := entity.FlowRun{}
	if err = tx.Find(&run, i.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	i.STEP = run.Step
	i.StepName = "审批中"
	if i.STEP == 1 {
		i.StepName = "申请中"
	}
	i.Progress = float64(act.Step*100) / float64(count)
	if i.Progress >= 100 && run.State == "0" {
		i.Progress = 95
	}
	i.Status = ""
	if run.State == "0" {
		i.Status = "active"
	} else if run.State == "2" {
		i.StepName = "已中止"
		i.Status = "exception"
	} else {
		i.StepName = "已完成"
		i.Status = "success"
	}

	return
}

func IndiClieDiviFlowAppXJKEF() base.EntityFunc {
	return func() interface{} {
		entity := IndiClieDiviFlowAppXJK{}
		return &entity
	}
}
func IndiClieDiviFlowAppXJKESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []IndiClieDiviFlowAppXJK
		return &entities
	}
}

func init() {
	dao := base.NewDefaultDao(IndiClieDiviFlowAppXJKEF(), IndiClieDiviFlowAppXJKESF(), nil)
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetAdditional("wfid", "25")
	dao.Fileter = &filter
	base.DaoPoolObj.Put("IndiClieDiviFlowAppXJK", dao)
}
